@file:Suppress("DEPRECATION")

package com.wanban.downloader.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.wanban.downloader.MultiDownloadManager
import com.wanban.downloader.R
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.notification.NotificationReceiver
import com.wanban.downloader.utils.Constants


class DownloadService : Service() {
    override fun onCreate() {
        super.onCreate()
        Log.e("DownloadService", "onCreate....")
        callStartForeground()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.e("DownloadService", "onStartCommand....")
        if (intent == null) return super.onStartCommand(intent, flags, startId)
        val action = intent.getIntExtra(Constants.INTENT_KEY_SERVICE_ACTION, -1)
        if (action <= -1) return super.onStartCommand(intent, flags, startId)
        when (action){
            // 恢复所有任务
            0 -> MultiDownloadManager.getDownloadManagers().forEach {
                it.resumeAllDownload()
            }
            1 -> { // 新增任务
                val task = (intent.getSerializableExtra(Constants.INTENT_KEY_SERVICE_TASK) as DownloadEntity?)?:return super.onStartCommand(intent, flags, startId)
                // 当前下载中的任务总数
                MultiDownloadManager.getDownloadManager(task.downloadType)?.startDownload(task)
            }
            2 -> { // 暂停下载
                val url = intent.getStringExtra(Constants.INTENT_KEY_SERVICE_DOWNLOAD_URL)?:return super.onStartCommand(intent, flags, startId)
                MultiDownloadManager.getDownloadManager(url)?.stopDownload(url)
            }
            3 -> { // 恢复下载
                val url = intent.getStringExtra(Constants.INTENT_KEY_SERVICE_DOWNLOAD_URL)?:return super.onStartCommand(intent, flags, startId)
                MultiDownloadManager.getDownloadManager(url)?.resumeDownload(url)
            }
            4 -> { // 删除下载
                val url = intent.getStringExtra(Constants.INTENT_KEY_SERVICE_DOWNLOAD_URL)?:return super.onStartCommand(intent, flags, startId)
                MultiDownloadManager.getDownloadManagers().forEach {
                    it.deleteDownload(url)
                }
            }
            5 -> { // 停止全部
                MultiDownloadManager.getDownloadManagers().forEach { it.stopAllDownload() }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)
        Log.e("DownloadService", "onStart....")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.e("DownloadService", "下载服务关闭....")
        super.onDestroy()
    }

    private fun callStartForeground() {
        val id = "com.wanban.downloader.id" //这里的id里面输入自己的项目的包的路径
        val intent = Intent()
        intent.setClass(this, NotificationReceiver::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }
        val notification: NotificationCompat.Builder //创建服务对象
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(id, "Download", NotificationManager.IMPORTANCE_MIN)
            channel.enableLights(false)
            channel.setShowBadge(true)
            channel.lockscreenVisibility = Notification.VISIBILITY_SECRET
            manager.createNotificationChannel(channel)
            notification = NotificationCompat.Builder(this).setChannelId(id)
        } else {
            notification = NotificationCompat.Builder(this)

        }
        notification.setVibrate(null).setSound(null).setLights(0, 0, 0).setContentTitle("下载").setContentText("启动下载服务！")
            .setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_download).setContentIntent(pendingIntent).setAutoCancel(true)
            .setDeleteIntent(pendingIntent).setOnlyAlertOnce(true)
        val builder = notification.build()
        builder.flags = Notification.FLAG_AUTO_CANCEL
        startForeground(1, builder) //这个就是之前说的startForeground
    }
}